class Tool < ActiveRecord::Base
  
  COLUMN_NAMES = ['','左栏','中栏','右栏']
  
  belongs_to :tool_type,:counter_cache => true
  has_one :tool_logo, :order => 'created_at desc'
  has_many :user_tool_settings
  
  validates_presence_of :code,
    :name,
    :version,
    :key_words,
    :synopsis,
    :introduce,
    :version_statement,
    :released_on,
    :month_fare
  
  validates_uniqueness_of :code,
    :name

  def logo
    tool_logo
  end
    
  def set_by_current_user?
    UserToolSetting.exists? [
      'user_id = ? and tool_id = ?',
      User.current_user_id, 
      id
    ]
  end
    
  def support_web?
    support_web == 'yes'
  end
  
  def support_sms?
    support_sms == 'yes'
  end
  
  def support_email?
    support_email == 'yes'
  end
  
  def flash?
    flash_embed.present?
  end
  
  def code
    self[:code] ? ActiveSupport::StringInquirer.new(self[:code]) : self[:code]
  end
  
  def others    
    Tool.all :order => 'rand()'
  end
  
  def others_support_sms
    Tool.all :conditions => [
      'support_sms = ? and id != ?',
      'yes',
      id
    ]
  end
  
  def title
    name + '- ' + key_words
  end
  
  def be_cared!
    update_attribute :carers_count, carers_count + 1
  end
  
  def updated_on
    updated_at.to_date
  end
  
  def embed!
    update_attribute :action_type ,'embed'
  end
  
  def popup!
    update_attribute :action_type ,'popup'
  end
  
  def embed_and_popup!
    update_attribute :action_type ,'embed_and_popup'
  end
  
  def embed?
    action_type == 'embed' or action_type == 'embed_and_popup'
  end
  
  def popup?
    action_type == 'popup' or action_type == 'embed_and_popup'
  end
  
  def action_type
    ActiveSupport::StringInquirer.new(self[:action_type])
  end

  def reset_user_tool_settings_count!
    Tool.reset_counters id, :user_tool_settings
  end
  
  def self.hot_top(limit = 10)
    all :order => 'user_tool_settings_count desc',
      :limit => limit
  end
  
  def self.new_top(limit = 10)
    all :order => 'released_on desc',
      :limit => limit
  end
end
